<template>
    <div :form="form" :table-data="tableData">
        <Col>
            <Card v-show="showSearch" dis-hover>
                <table-search @on-table-search="handleSearch">
                </table-search>
            </Card>
            <Card v-show="showBtnGroup" style="text-align: right" :padding="5">
                <Button v-show="showCreate" type="primary" icon="ios-add" @click="handleOpenCreate">新建</Button>
                <Button v-show="customizeCreate" type="primary" icon="ios-add" @click="handleOpenCustomizeCreate">新建</Button>
                <Button v-show="exportToExcelVisible" type="primary" icon="ios-add" @click="handleExportToExcel">导出到Excel</Button>
                <slot name="btnGroupExtBtn">
                    <!--额外按钮插槽-->
                </slot>
            </Card>
            <Card v-show="isShowFilterForm">
                <table-filter-form ref="tableFilterFormRef" v-if="isFilterFormRuleExtractInfoFormFields" :form-field-rule="filterFormRule" :label-width="filterFormLabelWidth" @on-submit-click="handlerTableFilterFormSubmit"></table-filter-form>
            </Card>
        </Col>
        <Col>
            <table-tool
                    v-show="showTool"
                    :top="top"
                    :left="left"
                    :select-num="selectNum"
                    @on-close-tool="handleCloseTool"
                    style="position: static;transform: none"
            >
                <tool-item @on-click="handleOpenUpdate" name="修改" v-show="selectNum===1 && showEdit"></tool-item>
                <tool-item @on-click="handleOpenDetail" name="查看详情" v-show="selectNum===1"></tool-item>
                <tool-item
                        v-for="(value,index) in extendTools"
                        :name="value.name"
                        @on-click="customEvent(value.event)"
                        v-show="value.show(selectNum,updateForm)"
                        :key="index"
                ></tool-item>
            </table-tool>
        </Col>
        <Col>
            <Card dis-hover v-show="showFilter">
                <custom-filter @on-delete-filter="handleDeleteFilter"
                               @on-save-filter="handleSaveFilter"
                               :filters="filters"
                               :fields="filterFields"
                               :select-filter-id="selectFilterId"
                               @on-click-filter="handleClickFilter">

                </custom-filter>
            </Card>
        </Col>
        <Col>
            <xinya-table @on-load-more="onLoadMore" height="" border ref="tables" :data="tableData" :columns="columns"
                         :form-columns="formColumns"
                         :showColumnSetting="showColumnSetting"
                         @on-row-dblclick="dbClick"
                         @on-select="onSelect"
                         @on-select-cancel="onSelectCancel"
                         @on-select-all="onSelectAll"
                         @on-selection-change="onSelectionChange"
                         @header-dragend="handleHeaderDragend"
                         @on-save-column-setting="handleCustomViewConfirm"
                         @on-cell-click="handleCellClick"
            >
            </xinya-table>
        </Col>
        <Col>
            <Card dis-hover v-show="showPage">
                <Page
                        ref="tablepage"
                        :total="total"
                        show-total
                        show-sizer
                        show-elevator
                        :current.sync="page"
                        :page-size="perPage"
                        :page-size-opts="pageSizeOpts"
                        @on-change="handlePageChange"
                        @on-page-size-change="handlePageSizeChange"
                />
            </Card>
        </Col>
        <form-field
                ref="formfield"
                :form="form"
                :title="formTitle.create"
                :reset-btn="true"
                @on-form-submit="handleCreate"
                @before-open="beforeOpen"
        >
            <template slot="extFormHeaderContent">
                <slot name="extFormHeaderContent">
                    <!--表单额外内容插槽-->
                </slot>
            </template>
            
        </form-field>
        <form-field
                ref="formupdate"
                :form="form"
                :title="formTitle.update"
                :default-value="updateForm"
                @on-form-submit="handleUpdate"
                @before-open="beforeOpen"
        >
            <template slot="extFormHeaderContent">
                <slot name="extFormHeaderContent">
                    <!--表单额外内容插槽-->
                </slot>
            </template>
            
        </form-field>
        <form-field
                ref="formdetail"
                :form="form"
                :title="formTitle.detail"
                :default-value="updateForm"
                :show-confirm="showConfirm"
                @before-open="beforeOpen"
                :is-show-bottom-btn="false"
                :detail-field-filter="true"
        >
    
            <template slot="extFormHeaderContent">
                <slot name="extFormHeaderContent">
                    <!--表单额外内容插槽-->
                </slot>
            </template>
            
        </form-field>
    </div>
</template>

<script>
    import {mapState, mapActions} from 'vuex';
    import pageconfig from '../configs/pageconfig';
    import FormField from '../components/FormField';
    import {deepCopy} from "../utils/helpers";
    import TableFilterForm from "./TableFilterForm";

    export default {
        name: "TableData",
        components: {
            TableFilterForm,
            FormField
        },
        props: {
            form: null,
            tableData: {
                type: Array,
                default() {
                    return [];
                }
            },
            total: {
                type: Number,
                default: 0
            },
            showSearch: {
                type: Boolean,
                default: false
            },
            isShowFilterForm    : {//是否展示搜索表单
                type   : Boolean,
                default: false
            },
            filterFormRule      : {//搜索表单字段信息
                type: Array,
                default() {
                    return [];
                },
            },
            filterFormLabelWidth: {//搜索表单字段label长度
                type   : Number,
                default: 90,
            },
            showPage: {
                type: Boolean,
                default: true
            },
            showFilter: {
                type: Boolean,
                default: true
            },
            extendTools: {
                type: Array,
                default() {
                    return [];
                }
            },
            showCreate: {
                type: Boolean,
                default: true
            },
	        customizeCreate: {
		        type: Boolean,
		        default: false
            },
            exportToExcelVisible: {
		        type: Boolean,
		        default: false
            },
            showBtnGroup: {
                type   : Boolean,
                default: true
            },
            showEdit: {
                type: Boolean,
                default: true
            },
            showTool: {
                type: Boolean,
                default: true
            },
            showColumnSetting: {
                type: Boolean,
                default: true
            }
        },
        data() {
            return {
                showConfirm: false,
                top: 30,
                left: 2,
                fields: [],
                updateForm: {},
                selectNum: 0,
                selectList: [],
                filters: [],
                selectFilterId: 1,
                columns: [],
                selectionColumns: [
                    {
                        type: "selection",
                        width: 60,
                        align: "center",
                        fixed: 'left',
                    }
                ],
                filterFields: [],
                formColumns: [],
                page: 1,
                perPage: pageconfig.DEFAULT_PAGE_SIZE,
                pageSizeOpts: pageconfig.PAGE_SIZE_OPTS,
                formTitle: {
                    create:'新建',
                    update:'更新',
                    detail:'详情查看',
                },
                isFilterFormRuleExtractInfoFormFields: false,//是否从表格字段定义中解析过搜索表单字段，如果解析过后开始渲染搜索表单
                tableFilterFormRef:'tableFilterFormRef',
                filterTabCurrentConditions:[],
            }
        },
        methods: {
            ...mapActions('customView', ['getCustomView', 'setCustomView', 'resizeCustomView']),
            ...mapActions('form', ['loadForm']),
            ...mapActions('filterGroup', ['getFilterGroup', 'createFilterGroup', 'updateFilterGroup', 'deleteFilterGroup']),
            customEvent(event) {
                let params;
                if (this.selectNum == 1) {
                    params = this.updateForm;
                } else {
                    params = this.selectList
                }
                this.$emit(event, params, () => {
                    this.$refs.tables.selectAll(false);
                });
            },
            handleCellClick(info, columnInfo) {
                this.$emit('on-cell-click', info, columnInfo);
            },
            handleOpenCreate() {
                this.$emit('on-create-btn-click');
                
                this.$refs.formfield.openForm();
            },
	        handleOpenCustomizeCreate() {
		        this.$emit('on-open-customize-create');
            },
            handleExportToExcel() {
                this.$emit('on-export-to-excel');
            },
            handleOpenUpdate() {
                //打开更新时的事件触发
                this.$emit('on-update-btn-click', this.updateForm);
                
	            this.$refs.formupdate.visible = true;
	            this.$refs.formupdate.setSpecialHeader();
            },
            handleOpenDetail() {
                this.$emit('on-detail-btn-click', this.updateForm);
    
                this.$refs.formdetail.visible = true;
            },
            handleCreate(formData) {
                this.$emit('on-form-create-click', formData, () => {
                    this.$refs.formfield.visible = false;
                });
            },
            handleUpdate(formData) {
                this.$emit('on-form-update-click', formData, this.updateForm.id, () => {
                    this.$refs.formupdate.visible = false;
                });
            },
            filterShowFields(fields) {
                this._filterFormRuleExtractInfoFormFields(fields);
                if (this.customViewRepository[this.form] === undefined) {
                    this.getCustomView({
                        formId: this.form,
                        success: () => {
                            this.columns = this.selectionColumns.concat(this.customViewRepository[this.form]);
                            this.formColumns = this.filterIsCustomView(fields);
                            this.filterFields = this.filterFilterFields(fields.fields);
                        }
                    });
                } else {
                    this.columns = this.selectionColumns.concat(this.customViewRepository[this.form]);
                    this.formColumns = this.filterIsCustomView(fields);
                    this.filterFields = this.filterFilterFields(fields.fields);
                }
            },
            _filterFormRuleExtractInfoFormFields(fields) {//从表格字段定义中提取搜索表单信息，如下拉框和标题
                let selectTypeName      = 'select',
                    optionsKeyName      = 'options',
                    fieldLabelKeyName   = 'label',
                    optionsValueProName = 'value',
                    optionTitleProName  = 'label';
                for (let filterRuleIndex in this.filterFormRule) {
                    let filterRuleInfo = this.filterFormRule[filterRuleIndex];
                    for (let fieldIndex in fields.fields) {
                        let filedInfo = fields.fields[fieldIndex];
                
                        //获取label
                        filedInfo.field_name === filterRuleInfo.fieldName
                        &&
                        !filterRuleInfo[fieldLabelKeyName]//如果未设置label 才使用表格定义的字段名称
                        &&
                        this.$set(this.filterFormRule[filterRuleIndex], fieldLabelKeyName, filedInfo.title);
                
                        //下拉选项值获取
                        if (
                            filterRuleInfo.fieldType === selectTypeName && !filterRuleInfo.remote
                            &&
                            filterRuleInfo[optionsKeyName] === undefined //未设置的情况下才获取
                            &&
                            filedInfo.field_type === selectTypeName && filedInfo.field_name === filterRuleInfo.fieldName
                        ) {//不为远程获取选项的字段
                    
                            //获取定义下拉选项
                            let options = filedInfo.field_options.map(val => {
                                return {
                                    [optionsValueProName]: val.value,
                                    [optionTitleProName] : val.title,
                                };
                            });
                    
                            this.$set(this.filterFormRule[filterRuleIndex], optionsKeyName, options);
                        }
                    }
            
                }
                this.isFilterFormRuleExtractInfoFormFields = true;
            },
            filterFilterFields(fields) {
                return deepCopy(fields).filter(value => {
                    return value.searchable == 1;
                });
            },
            refreshPage() {
                this.page = 1;
            },
            filterIsCustomView(fields) {
                let showFields = [];
                fields.fields.forEach(value => {
                    let tp = value;
                    if (tp.show_column == 1) {
                        showFields.push(value);
                    }
                });

                return showFields;
            },
            handlePageChange: function (page) {
                this.refreshSelectedNum();
                this.$emit('on-page-change', page);
            },
            handlePageSizeChange: function (pageSize) {
                this.refreshSelectedNum();
                this.$emit('on-page-size-change', pageSize);
            },
            handleCloseTool: function () {

            },
            onLoadMore: function () {
            },
            dbClick: function () {
            },
            onSelect: function () {
            },
            onSelectCancel: function () {
            },
            onSelectAll: function () {
            },
            onSelectionChange: function (selection) {
                let length = selection.length;
                this.selectNum = length;
                if (length === 1) {
                    this.updateForm = selection[0];
                } else {
                    this.selectList = selection;
                }
            },
            handleHeaderDragend: function (newWidth, oldWidth, column) {
                this.resizeCustomView({
                    id: column.id,
                    width: newWidth,
                    formId: this.form,
                    success: () => {
                        this.columns = this.selectionColumns.concat(this.customViewRepository[this.form]);
                    }
                });
            },
            handleSearch: function (value) {
                this.$emit('on-search-click', value);
            },
            handleSaveFilter: function (data, success, error) {
                if (data.id === undefined) {
                    this.createFilterGroup({
                        formId: this.form,
                        info: data,
                        success: (newFilter) => {
                            this.filters = this.filterGroupRepository[this.form];
                            this.selectFilterId = newFilter.id;
                            success();
                            this.$emit('filter-created', newFilter);
    
                            //触发表单和过滤tab修改事件
                            this.filterTabCurrentConditions = newFilter.conditions;
                            this.handlerFilterClickAndFilterFromSubmitCondition();
                        },
                        error: () => {
                            error();
                        }
                    });
                } else {
                    this.updateFilterGroup({
                        formId: this.form,
                        filterId: data.id,
                        info: data,
                        success: (newFilter) => {
                            this.filters = this.filterGroupRepository[this.form];
                            success();
                            this.$emit('filter-updated', newFilter);
                        },
                        error: () => {

                        }
                    });
                }
            },
            handleDeleteFilter: function (filterId) {
                this.deleteFilterGroup({
                    filterId: filterId,
                    formId: this.form,
                    success: () => {
                        this.filters = this.filterGroupRepository[this.form];
                    }
                });
            },
            handleClickFilter: function (selected) {
                this.refreshSelectedNum();
                this.refreshPage();
                this.selectFilterId = selected.id || 0;
                this.$emit('on-filter-click', selected);
    
                //触发表单和过滤tab修改事件
                this.filterTabCurrentConditions = selected.conditions;
                this.handlerFilterClickAndFilterFromSubmitCondition();
            },
            initFilterGroup: function (filterGroup) {
                this.filters = filterGroup;
                this.selectFilterId = (filterGroup[0] || []).id || 0;
            },
            handleCustomViewConfirm(columns) {
                this.setCustomView({
                    formId: this.form,
                    list: columns,
                    success: () => {
                        this.columns = this.selectionColumns.concat(this.customViewRepository[this.form]);
                        this.$emit('save-column-setting-end', columns);
                    }
                });
            },
            refreshSelectedNum() {
                this.selectNum = 0;
            },
            beforeOpen(setCustomProps) {
                this.$emit('before-form-open', this.updateForm, (props) => {
                    setCustomProps(props)
                })
            },
            handlerTableFilterFormSubmit(filterResultList) {//过滤表单提交触发事件
                this.refreshSelectedNum();
                this.refreshPage();
                this.$emit('on-filter-form-submit', filterResultList);
                this.handlerFilterClickAndFilterFromSubmitCondition();
            },
            handlerFilterClickAndFilterFromSubmitCondition(){
                let filterFormCondition = this.$refs[this.tableFilterFormRef].filterResult;
                this.$emit('on-filter-event', filterFormCondition.concat(this.filterTabCurrentConditions));
            },
        },
        computed: {
            ...mapState({
                customViewRepository: state => state.customView.userCustomViewRepository,
                formFieldRepository: state => state.form.formFieldRepository,
                filterGroupRepository: state => state.filterGroup.filterGroupRepository
            }),
        },
        created() {
            if (this.formFieldRepository[this.form] === undefined) {
                this.loadForm({
                    formId: this.form,
                    success: () => {
                        this.filterShowFields(this.formFieldRepository[this.form]);
                    }
                });
            } else {
                this.filterShowFields(this.formFieldRepository[this.form]);
            }
            if (this.filterGroupRepository[this.form] === undefined) {
                this.getFilterGroup({
                    formId: this.form,
                    success: () => {
                        this.initFilterGroup(this.filterGroupRepository[this.form]);
                    }
                });
            } else {
                this.initFilterGroup(this.filterGroupRepository[this.form]);
            }
        }
    }
</script>

<style scoped>
    .table-tool{
        height: auto;
    }
</style>